﻿/**
 * vue interceptors
 */
Vue.http.interceptors.push(function (request, next) {
    Loading(true);

    next(function (response) {
        Loading(false);

        if (response.status === 401) {
            dialogAlert('401,sorry,access deny!', 2);
        }

        if (response.status === 404) {
            dialogAlert('404,sorry,error address!', 2);
        }

        if (response.status === 400) {
            var message = "<span style='color:red;'>400,请检查以下错误:</span><br />";
            var errors = response.body;
            $.each(errors,
                function (i, propString) {
                    message += propString+'['+i+']' + "<br />";
                });
            
            dialogAlert(message,2);
        }

        if (response.status === 500) {
            console.log(response.data.ErrorMessage);
            console.log(response.data.ErrorStackTrace);
            dialogAlert(response.data.ErrorMessage, 2);
        }

        if (response.status === 200) {
            return response;
        }

    });
});

/**
 * Vue (带时间)过滤器
 */
Vue.filter('datetimeFormat', function (value, format) {
    if (format == undefined) {
        return formatDate(value, "yyyy-MM-dd HH:mm:ss");
    } else {
        return formatDate(value, format);
    }
});

/**
 * Vue 过滤器
 */

Vue.filter('dateFormat', function (value) {
    return $.dateFormat.date(value, "yyyy-MM-dd");
});



/**
 * vue components
 */
Vue.component('v-table', {
    template: '<table class="table table-striped table-bordered table-hover" v-bind:id="tableId"> \
                    <thead class="common-table-header" > \
                        <tr> \
                            <input data-order-name="" id="SearchEntity_OrderName" type="hidden" v-model="searchEntity.OrderName"> \
                            <input data-order-direction="" id="SearchEntity_OrderDirection" type="hidden" v-model="searchEntity.OrderDirection">\
                            <th class="text-center" style="background-color: white; width: 60px;"> \
                                <input class="common-table-checkbox-all" type="checkbox" v-model="checkAll" v-on:change="changeState()"> \
                            </th> \
                            <template v-for="(column, index) in gridColumns"> \
                                <th v-on:click="orderField(column.value)" v-bind:style="{\'width\':column.width?column.width:\'auto\'}" \
                                v-bind:class="{\'sorting\':column.sort,\'sorting_asc\':searchEntity.OrderDirection==\'0\' & searchEntity.OrderName==column.value,' +
    '\'sorting_desc\':searchEntity.OrderDirection==\'1\' & searchEntity.OrderName==column.value}" v-bind:data-order-field="column.value"> \
                                    {{ column.name }} \
                                </th> \
                            </template>  \
                        </tr> \
                    </thead> \
                    <tbody> \
                        <template v-for="(item, index) in gridDataSources">\
                            <tr v-on:click="selectRow(item[idColumn])" v-bind:class="{\'common-table-tr-selected\':selectedClass==item[idColumn]}"> \
                                <td align="center"> \
                                    <input type="checkbox" v-bind:index="index" v-bind:value="item[idColumn]" v-model="checkModel"> \
                                </td> \
                                <template v-for="(column, index) in gridColumns"> \
                                    <td v-bind:title="column.showTitle==undefined||column.showTitle?item[column.value]:false"> \
                                        <div v-bind:class="column.textClass" v-html="column.format?switchFormat(item,column.format):item[column.value]"> \
                                        </div>\
                                    </td> \
                                </template>\
                            </tr> \
                        </template> \
                    </tbody> \
               </table>',
    props: {

        /**
         * 每一列的定义，详见各参数
         * textClass:列的文本样式
         * name:列名称
         * value：列文本
         * sort：是否排序
         * width：列宽
         * format：列格式化函数
         * showTitle:是否显示title,默认显示， false不显示,
         */
        gridColumns: Object,

        /**
         * 列表数据
         */
        gridDataSources: [],

        /**
         * searchEntity 查询对象
         * OrderName:排序字段
         * OrderDirection：排序方向
         */
        searchEntity: Object,

        /**
         * grid的ID列，由父组件传递
         */
        idColumn: String

    },
    data: function () {
        return {
            /**
             * 全选复选框，默认不勾选
             */
            checkAll: false,

            /**
             * 选中行样式标记
             */
            selectedClass: '',

            /**
             * grid 选中行id集合
             */
            checkModel: [],

            /**
             * 表Id,随机值
             */
            tableId:new Date().getTime()
        }
    },
    watch: {
        /**
         * 全选、全不选切换
         */
        checkModel: {
            handler() {
                if (this.checkModel.length === this.gridDataSources.length) {
                    this.checkAll = true;
                } else {
                    this.checkAll = false;
                }
            },
            deep: true
        },
        gridDataSources: {
            handler() {
                this.clearSelected();
            },
            deep: true
        }
    },
    methods: {

        /**
         * 列排序方法
         * @param {} field 列名称
         * @returns {} void
         */
        orderField: function (field) {
            this.searchEntity.OrderName = field;
            this.searchEntity.OrderDirection = this.searchEntity.OrderDirection === "0" ? "1" : "0";
            this.$emit('get-list');
        },

        /**
         * 全选/全不选点击事件
         * @returns {} 
         */
        changeState: function () {
            this.checkModel = [];
            if (this.checkAll) {
                this.gridDataSources.forEach((value, index) => {
                    this.checkModel.push(value[this.idColumn]);
                });
            }
        },

        /**
         * 选中行样式切换
         * @param {} item 
         * @returns {} 
         */
        selectRow: function (item) {
            this.selectedClass = item;
        },

        /**
         * 清除选中项目
         * @returns {} 
         */
        clearSelected: function () {
            this.checkModel = [];
        },

        /**
         * 要求表格只能选择一条记录
         * @returns {} 
         */
        getSelectIndex: function () {
            if (this.checkModel.length < 1) {
                dialogMsg("请至少选择一行记录!", 0);
                return null;
            }
            else if (this.checkModel.length > 1) {
                dialogMsg("最多只能选择一行记录！", 0);
                return null;
            } 
            return parseInt($(":checkbox[class!='common-table-checkbox-all']:checked", "#" + this.tableId).attr("index"));
        },

        /**
         * 要求表格只能选择一条记录
         * @returns {} 
         */
        forceSelectOne: function () {
            if (this.checkModel.length < 1) {
                dialogMsg("请至少选择一行记录!", 0);
                return null;
            }
            else if (this.checkModel.length > 1) {
                dialogMsg("最多只能选择一行记录！", 0);
                return null;
            }
            return this.checkModel[0];
        },

        /**
         * 强列出所有选中值
         * @returns {} 
         */
        listSelectedValues: function () {
            return this.checkModel;
        },


        /**
         * 列出选中值
         * @returns {} 
         */
        listSelectedItems: function() {
            var selectedItem = this.listSelectedValues();

            var items = [];
            this.gridDataSources.forEach((value, index) => {
                if (selectedItem.includes(value[this.idColumn])) {
                    items.push(value);
                }
            });

            return items;
        },

        /**
         * 判断是否有选中数据
         * @returns {} 
         */
        isSelect: function () {

            if (this.checkModel.length < 1) {
                dialogMsg("请至少选择一行记录!", 0);
                return false;
            }
            return true;
        },

        /**
         * 格式转换
         * @param {} 整行记录 
         * @param {} 格式 
         * @returns {} 
         */
        switchFormat: function (record, format) {
            var paramsArray = format.substring(format.indexOf('(') + 1, format.indexOf(')')).split(',');
            
            paramsArray.forEach((value, index) => {
                if (value.indexOf('{') > -1) {
                    paramsArray[index] = record[value.replace(/\{|}/g, '')];
                } else {
                    paramsArray[index] = value.replace(/\'/g, '').replace(/\"/g, '');;
                }
            });

            /*
            chenjd（2017-8-9 10:01:13）：

            返回说明：两个参数，第一个是参数数组，第二个是当前记录
            1、原来参数会拼接成参数数组进行传递，花括号会被替换成相应数据
            2、当前整条记录会作为第二个参数进行传递。

            前台使用参数数组时注意，默认参数会全部转换成字符串类型

            */
            return this.$parent[format.substring(0, format.indexOf('('))].call(this, paramsArray, record);
        }

    }
});



Vue.component('v-pagination', {
    template: '<ul class="pagination" style="margin: 0px;">' +
    '<li><span style="padding:10.5px 15px;">第{{paginateHelperObject.PageIndex+1}}/{{paginateHelperObject.TotalPages}}页</span></li>' +
    '<li v-bind:key="index" v-for="(item,index) in pageList" v-bind:class="item.disabled">' +
    '<span style="padding: 10.5px 18px;" v-bind:class ="item.class" @click.stop="setPage(item)" v-bind:title="item.title"></span>' +
    '</li>' +
    '<li><span > 共 {{paginateHelperObject.TotalCount}} 条  每页 ' +
    '<select @change.stop="changePageSize()" title="每页显示数量" style="width:50px;display:inline;height:26px;border-radius: 5px;" class="form-control input-sm input-inline" v-model=paginateHelperObject.PageSize>' +
    '<option value="10">10</option>' +
    '<option value="20">20</option>' +
    '<option value="50">50</option>' +
    '<option value="100">100</option>' +
    '<option value="200">200</option>' +
    '<option value="500">500</option>' +
    '</select>条，查询耗时 {{costTime}} 毫秒</ul>',
    props: {
        paginateHelperObject: Object,
        costTime: Number,

        /**
         * searchEntity 查询对象
         * OrderName:排序字段
         * OrderDirection：排序方向
         */
        searchEntity: Object,
    },
    computed: {
        pageList: function () {
            var _this = this, pageList = [];
            //第一页
            pageList.push({
                class: 'fa fa-angle-double-left',
                page: 0,
                disabled: this.paginateHelperObject.PageIndex + 1 != 1 ? '' : 'disabled',
                html: '',
                title: '第一页'
            });

            //上一页
            pageList.push({
                class: 'fa fa-angle-left',
                page: this.paginateHelperObject.PageIndex - 1,
                disabled: this.paginateHelperObject.PageIndex != 0 ? "" : "disabled",
                html: '',
                title: '上一页'
            });

            //下一页
            pageList.push({
                class: 'fa fa-angle-right',
                page: this.paginateHelperObject.PageIndex + 1,
                disabled: this.paginateHelperObject.PageIndex < (this.paginateHelperObject.TotalPages - 1) ? "" : "disabled",
                html: '',
                title: '下一页'
            });

            //最后一页
            pageList.push({
                class: 'fa fa-angle-double-right',
                page: this.paginateHelperObject.TotalPages - 1,
                disabled: (this.paginateHelperObject.PageIndex + 1) < this.paginateHelperObject.TotalPages ? "" : "disabled",
                html: '',
                title: '最后一页'
            });


            return pageList;
        }
    },
    methods: {
        setPage: function (item) {
            if (item.disabled == '') {
                this.searchEntity.PageIndex = item.page;
                this.searchEntity.PageSize = this.paginateHelperObject.PageSize;
                this.$emit('get-list');
            }
        },
        changePageSize: function () {
            this.searchEntity.PageIndex = 0;
            this.searchEntity.PageSize = this.paginateHelperObject.PageSize;
            this.$emit('get-list');
        }
    }
});

/**
 * vue 日期插件
 */
Vue.component('v-datepicker',
    {
        template: '<input type="text" class="form-control input-wdatepicker" />',
        props: ['value'],
        mounted: function () {
            var vm = this;

            $(this.$el).datetimepicker({
                language: 'zh-CN',
                format: 'yyyy-mm-dd',
                minView: "month",
                initialDate: new Date(),
                autoclose: true
            })
            .val(this.value)
            .trigger('change')
            .on('change',
                function () {
                vm.$emit('input', this.value)
            });
        },
        watch: {
            value: function (value) {
                $(this.$el).val(value).trigger('change');
            }
        },
        destroyed: function () {
            $(this.$el).off().datepicker('destroy')
        }
    });


Vue.component('v-header',
    {
        template:  '<meta name="viewport" content="width=device-width" /><meta http-equiv="X-UA-Compatible" content= "IE=edge" > \
         <title>@ViewData["Title"]</title>\
         <link href="~/styles/font-awesome.min.css" rel="stylesheet" /> \
         <link href="~/scripts/bootstrap/bootstrap.min.css" rel="stylesheet" />\
         <link href="~/lib/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" /> \
         <link href="~/styles/learun-ui.css" rel="stylesheet" asp-append-version="true" />'
    });


Vue.component('v-footer',
    {
        template: 
        '<script src="~/scripts/plugins/jquery-ui/jquery-ui.min.js" ></script>' +
        ' <script src="~/scripts/bootstrap/bootstrap.min.js"></script>' +
        '<script src="~/lib/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script>' +
        ' <script src="~/lib/bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js"></script>' +
        '<script src="~/scripts/utils/learun-ui.js"></script>' +
        '<script src="~/scripts/utils/learun-form.js"></script>'+
        ' <script src="~/lib/jquery-extension.js"></script>' +
        ' <script src="~/lib/cls-page.js"></script>' +
        '' +
        ' '
    });